package com.zzj.压缩7z;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.sevenz.SevenZMethod;
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URL;

import static org.junit.Assert.assertEquals;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 小郑
 * Date: 2017-08-04
 * Time: 13:48
 */
public class Compress7z {
    public static File getFile(final String path) throws IOException {
        final URL url = Compress7z.class.getClassLoader().getResource(path);
        if (url == null) {
            throw new FileNotFoundException("couldn't find " + path);
        }
        URI uri = null;
        try {
            uri = url.toURI();
        } catch (final java.net.URISyntaxException ex) {
            throw new IOException(ex);
        }
        return new File(uri);
    }

    private void testSevenZArchiveCreation(final SevenZMethod method) throws Exception {
        final File output = new File( "d:\\004.zip");
        final File file1 = getFile("test1.xml");
        final File file2 = getFile("test2.xml");
        final SevenZOutputFile outArchive = new SevenZOutputFile(output);
        outArchive.setContentCompression(method);
        try {
            SevenZArchiveEntry entry;
            entry = outArchive.createArchiveEntry(file1, file1.getName());
            outArchive.putArchiveEntry(entry);
            copy(file1, outArchive);
            outArchive.closeArchiveEntry();

            entry = outArchive.createArchiveEntry(file2, file2.getName());
            outArchive.putArchiveEntry(entry);
            copy(file2, outArchive);
            outArchive.closeArchiveEntry();
        } finally {
            outArchive.close();
        }

        try (SevenZFile archive = new SevenZFile(output)) {
            SevenZArchiveEntry entry;
            entry = archive.getNextEntry();
            assert (entry != null);
            assertEquals(entry.getName(), file1.getName());
            entry = archive.getNextEntry();
        }
    }



    private void copy(final File src, final SevenZOutputFile dst) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(src);
            final byte[] buffer = new byte[8*1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) >= 0) {
                dst.write(buffer, 0, bytesRead);
            }
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

    @Test
    public void testSevenZArchiveCreationUsingLZMA2() throws Exception {
        testSevenZArchiveCreation(SevenZMethod.LZMA2);
    }




}
